package com.cl.pile.rule.filter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @author chenyitao
 * @date 2021/5/10
 */
public class BaseDateOperation {
    private final SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");

    private final String numRegex = "\\d+";

    public Date convertToDate(Object value) {
        if (value instanceof LocalDate) {
            LocalDate localDate = (LocalDate) value;
            return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        } else if (value instanceof LocalDateTime) {
            LocalDateTime localDateTime = (LocalDateTime) value;
            return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        } else if (String.valueOf(value).matches(numRegex) || (value instanceof Long) || (value instanceof Integer)) {
            return new Date(Long.parseLong(String.valueOf(value)));
        } else if (value instanceof String) {
            try {
                return sm.parse(String.valueOf(value));
            } catch (ParseException e) {
                return null;
            }
        }
        return null;
    }
}
